class WarehousesController < ApplicationController
  before_action :set_warehouse, only: [:show, :edit, :update, :destroy]

  respond_to :html

  def index
    @warehouses = Warehouse.where(build_search(search_params)).order(created_at: :desc).page(params[:page])

    respond_to do |format|
      format.html{}
      format.js {render :layout => false}
      format.json {render json:@warehouses }
    end
  end

  def show
    @products = @warehouse.products.order(created_at: :desc).page(params[:page])
    
    respond_with(@warehouse)
  end

  def new
    @warehouse = Warehouse.new
    respond_with(@warehouse)
  end

  def edit
  end

  def create
    @warehouse = Warehouse.new(warehouse_params)
    @warehouse.save
    respond_with(@warehouse)
  end

  def update
    @warehouse.update(warehouse_params)
    respond_with(@warehouse)
  end

  def destroy
    @warehouse.destroy
    respond_with(@warehouse)
  end

  private
    def set_warehouse
      @warehouse = Warehouse.find(params[:id])
    end

    def warehouse_params
      params.require(:warehouse).permit(:name)
    end
    
    def set_page_title
      @page_title = "仓库管理" 
    end
    
    def search_params     
        if params[:warehouse].present?  
          warehouse_params.permit(:name, products_attributes:[:id,:name,:desc,:unit,:quantity])
        end                     
    end
end
